package mywebapps.security.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import mywebapps.common.utils.HibernateUtil;
import mywebapps.security.dao.UserRoleDao;
import mywebapps.security.model.Role;
import mywebapps.security.model.UserRole;

/**
 * This is a Hibernate implementation for the UserRole DAO.
 * @author Paul Rivera (paul_mrivera@yahoo.com)
 *
 */
public class UserRoleDaoImpl implements UserRoleDao {

    @SuppressWarnings("unchecked")
    @Override
    public final Role[] getUserRoles(int userId) {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();

        Query query = session.getNamedQuery("Role.findRolesByUserId");
        query.setInteger("userId", userId);

        List<Object[]> results = (List<Object[]>) query.list();

        session.getTransaction().commit();

        Role[] roles = new Role[results.size()];
        for (int i = 0; i < results.size(); i++) {
            Object[] row = results.get(i);
            roles[i] = (Role) row[0];
        }

        return roles;
    }

    @Override
    public final void updateUserRoles(int userId, final List<Integer> newRoles) {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();

        Query query = session.getNamedQuery("UserRole.deleteUserRoles");
        query.setInteger("userId", userId);
        query.executeUpdate();

        for (int roleId : newRoles) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRole.setLastUpdateUser("BILLIBWEBAPP");
            session.save(userRole);
        }

        session.getTransaction().commit();
    }

}
